package com.wzh.project.utils.ssh2;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
 
public class InOutFile {
	
	
	public static void main(String[] args) {
		InOutFile t=new InOutFile();
		t.fileToByte(new File("C:\\Users\\wzh\\Desktop\\压测脚本\\temp.out"));
	}
	/**
	 * @param file null、一个文件、一个文件目录、
	 * <pre>
	 * fileToByte(null)=null
	 * fileToByte(file)=null file>2G
	 * fileToByte(文件目录)=null
	 * fileToByte(file)=byte[]
	 * </pre>
	 * @return null(文件不存在,null,文件目录,文件太大>2G) byte[](转换成功)
	 */
	public byte[] fileToByte(File file) {
		byte[] buffer = null;
		if (file == null) {
			throw new IndexOutOfBoundsException();
		}
		if (file.isDirectory())
			return buffer;
		if (file.length() > Integer.MAX_VALUE)
			return buffer;
		if (file.isFile()) {
			int filelength = (int) file.length();
			InputStream inputStream = null;
			BufferedInputStream bufferedInputStream = null;
			OutputStream outputStream=null;
			BufferedOutputStream bufferedOutputStream=null;
			File outfile=new File("files//out//"+file.getName());
			int n = 0;
			int off = 0;
			int length = 4096;
			try {
				if(!outfile.exists())
					outfile.createNewFile();
				inputStream = new FileInputStream(file);
				outputStream=new FileOutputStream(outfile, true);
				bufferedInputStream = new BufferedInputStream(inputStream);
				bufferedOutputStream=new BufferedOutputStream(outputStream);
				buffer = new byte[filelength];
				/*
				 * 添加(length <= filelength - off) ? length : filelength - off)的比较
				 * 为了防止读到最后buffer 剩余的长度没有4096 装不下那么多会导致读取不了IndexOutOfBoundsException()
				 * 当filelength - off=0时表示文件读取完毕但是read内部认为是其他线程占用io导致堵塞并不会认为文件读取完毕
				 * 所以要添加上filelength - off>0
				 */
				while ((filelength - off) > 0 && (n = bufferedInputStream.read(buffer, off,
						((length <= filelength - off) ? length : filelength - off))) >= 0) {
					bufferedOutputStream.write(buffer, off, n);
					off += n;
				}
			}
			catch (Exception e) {
			}
			finally {
				closeInputStream(bufferedInputStream);
				closeInputStream(inputStream);
				closeOutputStream(bufferedOutputStream);
				closeOutputStream(outputStream);
				System.out.println("end");
			}
		}
		return buffer;
	}
 
	/**
	 * close inoutstream
	 * @param inputStream null or the inputstream's child
	 */
	private void closeInputStream(InputStream inputStream) {
		if (inputStream == null)
			return;
		try {
			inputStream.close();
		}
		catch (Exception e) {
		}
	}
	/**
	 * close outputStream
	 * @param outputStream null or the outputStream child
	 */
	private void closeOutputStream(OutputStream outputStream) {
		if (outputStream == null)
			return;
		try {
			outputStream.flush();
			outputStream.close();
		}
		catch (Exception e) {
		}
	}
}